package servlet;

import entity.User;
import service.UserService;

import javax.servlet.*;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.*;
import java.io.IOException;
import java.util.HashMap;

@WebServlet("/LoginServlet")
public class LoginServlet extends HttpServlet {
    private UserService userService = new UserService();

    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        request.setCharacterEncoding("UTF-8");
        response.setCharacterEncoding("UTF-8");
        String username = request.getParameter("username");
        String password = request.getParameter("password");
        String userId = request.getParameter("userId");
        String roleId = request.getParameter("roleId");
        String sex = request.getParameter("sex");
        String peiceName = request.getParameter("peiceName");
        String phone  = request.getParameter("phone");
        String province = request.getParameter("province");
        String district = request.getParameter("district");
        String detailAddress  = request.getParameter("detailAddress");

        //调用服务层验证用户名和密码
        boolean isValid = userService.isLogin(username, password);

        // 根据验证结果进行重定向
        if (isValid) {
            HttpSession session = request.getSession();
            // 验证成功，
            HashMap<String, String> user = userService.getUserInfoByUsername(username);
           session.setAttribute("user", user);

            // 根据角色Id重定向到不同页面
            String roleIdStr = user.get("roleId");
            if ("2".equals(roleIdStr)) {
                response.sendRedirect("index.jsp"); // 用户登录跳转到首页
            } else if ("1".equals(roleIdStr)) {



                //！！这里是我举例的页面，需要修改
                response.sendRedirect("shopHome.jsp"); // 店铺登录跳转到店铺主页





            } else {
                // 其他角色，可以根据需要重定向到其他页面或显示错误
                response.sendRedirect("error.jsp"); // 示例：重定向到错误页面
            }
        } else {
            // 验证失败，重定向到登录页面
            request.setAttribute("errorMessage", "用户名或密码错误");
            response.sendRedirect("login.jsp?error=true");
        }
    }

    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        doPost(request, response);
    }
}